package com.mxprojects.gui
{
	import com.mxprojects.constructors.ButtonLarge;
	import com.mxprojects.constructors.PopupWindow;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	import com.mxprojects.views.LoginDialog;
	
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	
	public class DefaultDialog
	{
		private static const POPUP_WIDTH:int = 300;
		private static const POPUP_HEIGHT:int = 200;
		
		protected static var popup:PopupWindow;
		protected static var showStage:Boolean;
		protected static var closeFunction:Function;
		
		public function DefaultDialog(){}
		
		public static function show(message:String, showStageOnClose:Boolean = true, titleFromWord:String = Word.ERROR, functionToRunOnClose:Function = null):void {
			
			//if it's already on the stage, close it
			if(popup != null){
				closeDialog();
			}
			
			//if we show the stage when the window closes
			showStage = showStageOnClose;
			
			//set a close function if they got it
			closeFunction = functionToRunOnClose;
			
			//build the popup
			createPopup(Language.main(titleFromWord, true));
			var close:ButtonLarge = popup.createActionButton(Language.main(Word.CLOSE), closeDialog);
			popup.createTextBlock(message, closeDialog);
			
			//if the login box is up, disable the listeners
			if(LoginDialog.loginDialog != null){
				LoginDialog.stopListeningToKeys();
			}
			
			
		}
		
		protected static function createPopup(title:String):void {
			popup = new PopupWindow(POPUP_WIDTH, POPUP_HEIGHT, title, closeDialog, false);
			
			//listen for enter or esc to close the window
			popup.stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyboard, false, 0, true); 
		}
		
		protected static function closeDialog(event:MouseEvent = null):void {
			if(popup != null){
				popup.stage.removeEventListener(KeyboardEvent.KEY_DOWN, checkKeyboard);
				popup.removeFromStage(null, showStage);
				popup = null;
				
				//if there is something else we need to do when the window is closed
				if(closeFunction != null){
					closeFunction();
				}
				
				//if the login box is up, enable the listeners
				if(LoginDialog.loginDialog != null){
					LoginDialog.listenToKeys();
				}
			}
		}
		
		private static function checkKeyboard(event:KeyboardEvent):void {
			if(event.keyCode == Keyboard.ENTER || event.keyCode == Keyboard.ESCAPE){
				closeDialog();
			}
		}

	}
}